package com.shxt.framework.rbac.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import com.shxt.framework.commons.controller.BaseController;
import com.shxt.framework.commons.exception.LoginAccountExceiption;
import com.shxt.framework.commons.exception.ServiceExceiption;
import com.shxt.framework.rbac.menu.service.MenuService;
import com.shxt.framework.rbac.user.model.User;
import com.shxt.framework.rbac.user.service.UserService;

@Controller
public class LoginController extends BaseController {
	@Autowired
	private UserService userService;
	@Autowired
	private MenuService menuService;

	@GetMapping({"/","/sys/login"})
	public String login() {
		return "login";
	}

	@PostMapping("/sys/login")
	public String login(String account,String password,Model model) {
		try {
			User user = this.userService.login(account, password);
			//登录成功之后，将用户信息保存到Session范围
			this.session.setAttribute("session_user", user);
			return "redirect:/sys/main";
		} catch (LoginAccountExceiption | ServiceExceiption ex) {
			model.addAttribute("message", ex.getMessage());
			return "login";
		}
	}

	@GetMapping("/sys/main")
	public String main(Model model) {
		//1.获取Session中的用户信息
		User user = (User) this.session.getAttribute("session_user");
		Integer roleId = user.getRole_id();
		if (roleId != null) {
			model.addAttribute("childMenus", this.menuService.getChildMenuList(roleId));
			model.addAttribute("parentMenus", this.menuService.getParentMenuList(roleId));
		}

		return "main";
	}

	@GetMapping("/sys/logout")
	public String logout() {
		this.session.invalidate();//注销所有的session
		return "redirect:/sys/login";
	}
}
